package com.ficus.road.maintain.task;

import com.ficus.road.maintain.core.model.GpsHistory;
import com.ficus.road.maintain.core.model.GpsLocation;
import com.ficus.road.maintain.core.model.TheoryGps;
import com.ficus.road.maintain.dao.GpsHistoryDao;
import com.ficus.road.maintain.dao.coverage.CoverageFixManualDao;
import com.ficus.road.maintain.service.CoverageFixManualService;
import com.ficus.road.maintain.service.CycleNumService;
import com.ficus.road.maintain.third.zh.roadgps.ZHRoadName;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 手动修复覆盖率
 *
 * @author xiawen yang
 * @date 2022/4/26 下午1:53
 */
@Component
@Slf4j
public class CoverageFixManualTask {
    @Autowired
    private GpsHistoryDao gpsHistoryDao;
    @Autowired
    private CoverageFixManualService coverageFixManualService;
    @Autowired
    private CoverageFixManualDao coverageFixManualDao;
    @Autowired
    private CycleNumService cycleNumService;
    @Autowired
    private ZHRoadName zhRoadName;

    /**
     * 每个新的周期开始时, 创建待修复的点集
     */
//    @Scheduled(cron = "0 0 0 * * ?")
    public void createToBeFixedPoints() {
        if (!cycleNumService.judgeFirstDateOfCycleNum()) {
            return;
        }
        log.info("开始创建待修复点集...");
        coverageFixManualService.createTheoryGpsBySamples();
        log.info("待修复点集创建成功!");
    }

    /**
     * 更新待修复点集
     */
//    @Scheduled(cron = "0 5 * * * ?")
    @Scheduled(cron = "${coverage.fix_cron}")
    public void updateToBeFixedPoints() {
        // 找出自动修复后，且待手动修复的点集
        List<GpsHistory> toBeManualFix = gpsHistoryDao.findByQuery(new Query(Criteria.where("is_fixed").is(Boolean.TRUE).and("is_manual_fixed").is(Boolean.FALSE)));
        toBeManualFix.stream().forEach(gpsHistory -> {
            gpsHistory.setIsManualFixed(Boolean.TRUE);
            gpsHistoryDao.saveOrUpdate(gpsHistory);
            TheoryGps theoryGps = coverageFixManualService.geoSearch(gpsHistory);
            if (ObjectUtils.isEmpty(theoryGps)) {
                return;
            }
            theoryGps.setIsCovered(Boolean.TRUE);
            coverageFixManualDao.saveOrUpdate(theoryGps);
        });
    }

    //    @Scheduled(cron = "0/5 * * * * ?")
    public void test() {
        String roadName = zhRoadName.getRoadName(GpsLocation.builder().longitude(121.70294724).latitude(31.185533029).build());
        System.out.println(roadName);
    }
}
